// 任务一：查询特定用户及其角色
async function getUserWithRoles() {
    const username = document.getElementById('username').value;
    if (!username) {
        alert('请输入用户名');
        return;
    }

    try {
        const response = await fetch(`user?method=getUserWithRoles&username=${username}`);
        const result = await response.json();

        if (result.code === 200) {
            const user = result.data;
            let html = `<h3>用户信息：${user.name}</h3>`;
            html += `<p>登录名：${user.loginname}</p>`;
            html += `<p>邮箱：${user.email}</p>`;
            html += `<p>角色列表：</p><ul>`;
            user.roles.forEach(role => {
                html += `<li>${role.name} - ${role.description}</li>`;
            });
            html += `</ul>`;
            document.getElementById('userResult').innerHTML = html;
        } else {
            alert(result.message);
        }
    } catch (error) {
        console.error('Error:', error);
        alert('查询失败');
    }
}

// 任务三：条件搜索用户
async function searchUsers() {
    const username = document.getElementById('searchUsername').value;
    const email = document.getElementById('searchEmail').value;
    const status = document.getElementById('searchStatus').value;

    const params = new URLSearchParams();
    params.append('method', 'searchUsers');
    if (username) params.append('username', username);
    if (email) params.append('email', email);
    if (status) params.append('status', status);

    try {
        const response = await fetch(`user?${params}`);
        const result = await response.json();

        if (result.code === 200) {
            const users = result.data;
            let html = '<h3>搜索结果：</h3>';
            users.forEach(user => {
                html += `<div class="user-card">`;
                html += `<h4>${user.name} (${user.loginname})</h4>`;
                html += `<p>邮箱：${user.email} | 状态：${user.status === 0 ? '正常' : '禁用'}</p>`;
                html += `<p>角色：${user.roles.map(r => r.name).join(', ')}</p>`;
                html += `</div>`;
            });
            document.getElementById('searchResult').innerHTML = html;
        } else {
            alert(result.message);
        }
    } catch (error) {
        console.error('Error:', error);
        alert('搜索失败');
    }
}